package com.healthcloud.ssh;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.util.Properties;


/**
 * @author wangdi
 * @since 2024/9/12
 */


public class SshConnectionTool {
    //本地的ssh中的knownhost文件路径
    private final static String S_PATH_FILE_KNOWN_HOSTS = "C:/Users/wd/.ssh/known_hosts";
    //本地的ssh密钥路径
    private final static String S_PATH_FILE_PRIVATE_KEY = "C:/Users/wd/.ssh/id_rsa";

    //ssh连接的用户名
    private final static String SSH_USER = "root";
    //ssh远程连接的ip地址
    private final static String SSH_REMOTE_SERVER = "183.134.77.195";
    //ssh连接的端口号
    private final static int SSH_REMOTE_PORT = 22;
    //本地mysql发起连接的IP地址
    private final static String MYSQL_REMOTE_SERVER = "127.0.0.1";
    //本地数据库连接时用的端口号
    private final static int LOCAl_PORT = 6032;
    //远程数据库端口用的端口号
    private final static int REMOTE_PORT = 6032;

    private Session sesion; //ssh 会话

    public SshConnectionTool() throws Throwable {

        JSch jsch = null;

        jsch = new JSch();
        //设置known_hosts文件路径，如：~/.ssh/known_hosts（known_hosts中存储是已认证的远程主机host key）
        jsch.setKnownHosts(S_PATH_FILE_KNOWN_HOSTS);
        //设置私钥
        jsch.addIdentity(S_PATH_FILE_PRIVATE_KEY);

        sesion = jsch.getSession(SSH_USER, SSH_REMOTE_SERVER, SSH_REMOTE_PORT);

        //设置连接过程不校验known_hosts文件中的信息
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        sesion.setConfig(config);
        sesion.setTimeout(10000000);
        sesion.connect(); //ssh 建立连接！

        //根据安全策略，您必须通过转发端口进行连接
        sesion.setPortForwardingL(LOCAl_PORT, MYSQL_REMOTE_SERVER, REMOTE_PORT);
        sesion.setPortForwardingL(6379, "192.168.0.148", 6379);
//        sesion.setPortForwardingL(5672, "192.168.0.148", 5672);
        sesion.setPortForwardingL(5672, "192.168.0.148", 5672);

    }

    public void closeSSH() {
        sesion.disconnect();
    }


}